package ch.ra.dev.nastywheel.activity;

import java.util.ArrayList;
import java.util.List;

import ch.ra.dev.nastywheel.util.Contact;
import ch.ra.dev.nastywheel.util.Keys;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.ContactsContract;

public class ReadContactActivity extends Activity {


	private List<Contact> contacts = new ArrayList<Contact>();
	
	public List<Contact> getContacts() {
		return contacts;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		readContacts();
	}
	
	public void readContacts() {
		String displayName; 
		String phoneNumber; 

		Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; 

		String[] PHONES_PROJECTION = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };

		String PHONE_SELECTION = null; 
		
		contacts.clear();
		
		String[] projection = new String[] {
	            ContactsContract.Contacts._ID,
	            ContactsContract.Contacts.DISPLAY_NAME,
	            ContactsContract.Contacts.HAS_PHONE_NUMBER,
	    };
		
		String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";
		
		Cursor contactCursor = getContentResolver().query(
					ContactsContract.Contacts.CONTENT_URI, projection, selection, null, null); 		

		if(contactCursor.getCount() <= 0) {
			finish();
			return;
		}
		
		contactCursor.moveToFirst();

        do {
			long contactId = contactCursor.getLong(contactCursor.getColumnIndex(ContactsContract.Contacts._ID)); 
			
			PHONE_SELECTION = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId; 
			
			Cursor phones = getContentResolver().query(phoneUri,
			   PHONES_PROJECTION,
			   PHONE_SELECTION, 
			   null,
			   ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY + " DESC");
			
			if(phones.getCount() > 0) {
				phones.moveToFirst(); 
				
				phoneNumber = phones.getString(
						 phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("\\D", "");
				
				displayName = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
				
				contacts.add(new Contact(displayName, phoneNumber));
			}
			
        } while(contactCursor.moveToNext()); 

        contactCursor.close(); 

	    Intent intent = new Intent(Keys.READ_CONTACTS);
	    Bundle bundle = new Bundle();
	    bundle.putParcelableArrayList(Keys.CONTACTS, (ArrayList<? extends Parcelable>) contacts);
	    
	    intent.putExtra(Keys.CONTACTS_BUNDLE, bundle);
	    sendBroadcast(intent);
	    finish();
	}
}
